package org.example.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.domain.Order;
import org.example.model.Result;
import org.example.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("order/order")
@Api(tags = "后台管理系统订单接口管理")
public class SysOrderServiceController {

    @Autowired
    private OrderService orderService;

    @ApiOperation("多条件分页查询订单")
    @GetMapping("/page")
    @PreAuthorize("hasAuthority('order:order:page')")
    public Result<Page<Order>> loadOrderPage(@RequestParam Long current,
                                             @RequestParam Long size,
                                             @RequestParam(required = false) String orderNumber,
                                             @RequestParam(required = false) Integer status,
                                             @RequestParam(required = false) Date startTime,
                                             @RequestParam(required = false) Date endTime) {
        // 创建订单分页对象
        Page<Order> page = new Page<>(current, size);
        // 多条件分页查询订单
        page = orderService.queryOrderPage(page, orderNumber, status , startTime, endTime);
        return Result.success( page);
    }

    @ApiOperation("根据订单编号查询订单详情")
    @GetMapping("/orderInfo/{orderNumber}")
    @PreAuthorize("hasAuthority('order:order:info')")
    public Result<Order> loadOrderDetail(@PathVariable Long orderNumber) {
        Order order = orderService.queryOrderDetailByOrderNumber(orderNumber);
        return Result.success( order);
    }

    @ApiOperation("导出销售记录")
    @GetMapping("/soldExcel")
    @PreAuthorize("hasAuthority('order:order:soldExcel')")
    public Result<String> exportSoLeOrderRecordExcel( ) {
        // 查询所有销售记录
        List<Order> list = orderService.list( new LambdaQueryWrapper<Order>()
                .orderByDesc( Order::getCreateTime));


        String fileName = "E:\\Excels\\" + System.currentTimeMillis() + ".xlsx";

        // 使用 EasyExcel 写入输出流
        EasyExcel.write(fileName, Order.class)
                .sheet("销售明细")
                .doWrite(list);
        return Result.success( null);
    }

}
